package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//回响服务器 UDP的socket
public class netEchoServer {
    DatagramSocket socket = null;//用来接受发过来的请求和发出请求

    private int ServerPort;//记录端口

    public netEchoServer(int port) {
        ServerPort = port;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);//接受请求的载体
            //接受发过来的请求
            socket.receive(packet);//没接受到请求他就会阻塞等待
            //解析请求并对他进行操作然后返回
            //解析发回来的要用的数据 要使用String来获取发送的内容
            String request = new String(packet.getData(), 0, packet.getLength());
            String response = run(request);
            //对返回值包装然后送回
            //包装结果
            DatagramPacket returnPacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    packet.getAddress(), packet.getPort());
            //发送回去
            socket.send(returnPacket);
            //打印日志看看发生了什么 服务器的位置 端口  请求  返回请求
            System.out.printf("[%s:%d]  request:%s  response:%s\n", packet.getAddress().toString(), packet.getPort(),
                    request, response);
        }
    }


    private String run(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        netEchoServer net = new netEchoServer(9090);//自己设置端口
        net.start();
    }
}





















